import {
  articleCollectionDelete,
  articleCollectionPost,
  articleLikings,
  articleLikingsDelete,
  articlesGet,
  commentsGet,
  commentsPost,
  userFollowingsDelete,
  userFollowingsPost
} from '@/api'
import { ArticleInfoType, CommParamsType, commReqType } from '@/types/data'
import { RootThunkAction } from '@/types/store'
// 获取文章详情的 action
function getArticleInfoAction (id: string): RootThunkAction {
  return async dispatch => {
    const res = await articlesGet(id)
    // console.log(res)

    dispatch({ type: 'articleInfo/save', payload: res.data.data })
  }
}
// 点赞的 action
function likeArticleAction (id: string, attitude: number): RootThunkAction {
  return async dispatch => {
    if (attitude === -1) {
      await articleLikings(id)
    } else {
      await articleLikingsDelete(id)
    }
    await dispatch(getArticleInfoAction(id))
  }
}
// 收藏的 action
function toggleFollowArticleAction (id: string): RootThunkAction {
  return async (dispatch, getState) => {
    const info = getState().articleInfo as ArticleInfoType
    if (info.is_collected) {
      await articleCollectionDelete(id)
    } else {
      await articleCollectionPost(id)
    }
    await dispatch(getArticleInfoAction(id))
  }
}
// 关注用户的 action
function userFollowAction (): RootThunkAction {
  return async (dispatch, getState) => {
    const info = getState().articleInfo as ArticleInfoType
    const id = info.aut_id
    if (info.is_followed) {
      await userFollowingsDelete(id)
    } else {
      await userFollowingsPost(id)
    }
    await dispatch(getArticleInfoAction(info.art_id))
  }
}
// 评论的action
function commentsGetAction (params: CommParamsType): RootThunkAction {
  return async (dispatch, getState) => {
    const res = await commentsGet(params)
    // console.log(res)
    dispatch({ type: 'article/Comm', payload: res.data.data })
  }
}
// 加载更多评论

function loadCommentsGetAction (source: string): RootThunkAction {
  return async (dispatch, getstate) => {
    const { last_id } = getstate().comm
    const res = await commentsGet({ type: 'a', source, offset: last_id })
    // console.log(res)
    dispatch({ type: 'load/Comm', payload: res.data.data })
  }
}
// 写评论

function addCommentAction (data: commReqType): RootThunkAction {
  return async (dispatch, getstate) => {
    const res = await commentsPost(data)
    // console.log(res)
    dispatch({ type: 'add/load/Comm', payload: res.data.data.new_obj })
  }
}

export {
  getArticleInfoAction,
  likeArticleAction,
  toggleFollowArticleAction,
  userFollowAction,
  commentsGetAction,
  loadCommentsGetAction,
  addCommentAction
}
